const models = require('./../db/mysqldb/index')
const { ErrorModel, SuccessModel, encrypt } = require('./../utils/index')
const config = require('./../config/index')
const logger = require('./../utils/logger')
class SystemController {
  static async init (req, res, next) {
    try {
      await models.sequelize.sync({})
      await res.json(new SuccessModel(`mysql table create success`))
    } catch (error) {
      await res.json(new ErrorModel(`错误信息：${error.message}`))
    }
  }
  static async addAdmin (req, res, next) {
    try {
      const password = await encrypt(config.admin_password, config.saltTime)
      const deptRes = await models.sys_dept.create({
        dept_id: 1,
        dept_name: '超级权限部门',
        parent_id: 0,
        sort: 0
      })
      logger.info(`SystemController`, `addAdmin`, deptRes)
      const deptRelationRes = await models.sys_dept_relation.create({
        ancestor: 1,
        descendant: 1
      })
      logger.info(`SystemController`, `addAdmin`, deptRelationRes)
      const menuList = [
        {
          menu_id: 0,
          name: '首页',
          path: '/',
          parent_id: 1,
          component: 'page/wel',
          sort: 1,
          type: '0'
        }, {
          menu_id: 1,
          name: '系统管理',
          path: 'admin',
          icon: 'icon-xitongguanli',
          parent_id: -1,
          component: 'Layout',
          sort: 10,
          type: '0'
        }, {
          menu_id: 2,
          name: '用户管理',
          path: 'user',
          parent_id: 1,
          icon: 'icon-yonghuguanli',
          component: 'views/admin/user/index',
          sort: 2,
          type: '0'
        },
      ]
      const menuRes = await models.sys_menu.bulkCreate(menuList)

      logger.info(`SystemController`, `addAdmin`, menuRes)
      const roleRes = await models.sys_role.create({
        role_id: 1,
        role_name: 'admin',
        role_code: 'admin',
        role_desc: '超级管理员'
      })
      logger.info(`SystemController`, `addAdmin`, roleRes)
      const userRes = await models.sys_user.create({
        user_id: 1,
        username: 'admin',
        password,
        realname: 'admin',
        phone: '17034642112',
        dept_id: 1,
      })
      logger.info(`SystemController`, `addAdmin`, userRes)
      const roleMenu = await models.sys_role_menu.create({
        role_id: 1,
        menu_id: 1,
      })
      logger.info(`SystemController`, `addAdmin`, roleMenu)
      const userRole = await models.sys_role_user.create({
        role_id: 1,
        user_id: 1,
      })
      logger.info(`SystemController`, `addAdmin`, userRole)
      await res.json(new SuccessModel(`admin create success`))
    } catch (error) {
      logger.info(`SystemController`, `addAdmin`, error.message)
      await res.json(new ErrorModel(`错误信息：${error.message}`))
    }
  }
}

module.exports = {
  SystemController
}
